package com.sokal.easycare.modules.picture.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sokal.easycare.common.persistence.Page;
import com.sokal.easycare.common.service.CrudService;
import com.sokal.easycare.common.utils.StringUtils;
import com.sokal.easycare.modules.picture.entity.PicArticle;
import com.sokal.easycare.modules.picture.dao.PicArticleDao;
import com.sokal.easycare.modules.picture.entity.PicArticleFile;
import com.sokal.easycare.modules.picture.dao.PicArticleFileDao;

/**
 * 图文内容Service
 * @author liliangdong
 * @version 2017-03-22
 */
@Service
@Transactional(readOnly = true)
public class PicArticleService extends CrudService<PicArticleDao, PicArticle> {

	@Autowired
	private PicArticleFileDao picArticleFileDao;
	
	public PicArticle get(String id) {
		PicArticle picArticle = super.get(id);
		picArticle.setPicArticleFileList(picArticleFileDao.findList(new PicArticleFile(picArticle)));
		return picArticle;
	}
	
	public List<PicArticle> findList(PicArticle picArticle) {
		return super.findList(picArticle);
	}
	
	public Page<PicArticle> findPage(Page<PicArticle> page, PicArticle picArticle) {
		return super.findPage(page, picArticle);
	}
	
	@Transactional(readOnly = false)
	public void save(PicArticle picArticle) {
		super.save(picArticle);
		for (PicArticleFile picArticleFile : picArticle.getPicArticleFileList()){
			if (picArticleFile.getId() == null){
				continue;
			}
			if (PicArticleFile.DEL_FLAG_NORMAL.equals(picArticleFile.getDelFlag())){
				if (StringUtils.isBlank(picArticleFile.getId())){
					picArticleFile.setPicArticle(picArticle);
					picArticleFile.preInsert();
					picArticleFileDao.insert(picArticleFile);
				}else{
					picArticleFile.preUpdate();
					picArticleFileDao.update(picArticleFile);
				}
			}else{
				picArticleFileDao.delete(picArticleFile);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(PicArticle picArticle) {
		super.delete(picArticle);
		picArticleFileDao.delete(new PicArticleFile(picArticle));
	}
	
}